<?php

namespace App\Http\Controllers\Web;

use App\Models\Products;
use App\Models\ProductsChildren;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use function PHPUnit\Framework\isEmpty;

class ProductsChildrenController extends Controller
{
    public function index(Request $request)
    {
        $size = $request->input('size', 10);
        $type = $request->input('type');
        $query = ProductsChildren::query()->with('products')->whereHas('Products', function ($query) use ($type) {
            if (!empty($type)) {
                $query->where('type', $type);
            }
        });
        $product_id = $request->input("product_id");

        $query->when($product_id, function ($query) use ($product_id) {
            $query->where('product_id', $product_id);
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        $requestData = $this->validate($request, [
            'number' => 'required',
            'name' => 'required',
            'name_en' => 'nullable',
            'icon_url' => 'required',
            'product_id' => 'required',
            'introduction' => 'required',
            'introduction_en' => 'nullable',
            'applicable_fields' => 'required',
            'applicable_fields_en' => 'nullable',
            'certificate' => 'required',
            'certificate_en' => 'nullable',
            'application_scenarios' => 'required',
            'parameter_name' => 'required',
            'parameter_name_en' => 'nullable',
            'parameter_img_url' => 'required',
            'applicable_parts' => 'required',
            'applicable_parts_en' => 'nullable',
            'storage' => 'required',
            'storage_en' => 'nullable',
            'packing' => 'required',
            'packing_en' => 'nullable',

        ]);
        return $requestData;
    }

    public function show($id)
    {
        $product = ProductsChildren::query()->findOrFail($id);
        return $this->success($product);
    }

    public function store(Request $request)
    {
        $product = new ProductsChildren;
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function update(Request $request, $id)
    {
        $product = ProductsChildren::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $product->fill($requestData);
        $product->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $product = ProductsChildren::query()->findOrFail($id);
        $product->delete();
        return $this->success();
    }
}
